package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.EwsUserDao;
import com.egoo.ticket.server.dao.EwsUserRoleDao;
import com.egoo.ticket.server.dao.WorkOrderTypeNodeDao;
import com.egoo.ticket.server.pojo.entity.EwsUser;
import com.egoo.ticket.server.pojo.entity.EwsUserRole;
import com.egoo.ticket.server.pojo.vo.InteractiveDataVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTypeNodeVo;
import com.egoo.ticket.server.service.EurmDataSyncService;
import com.egoo.ticket.server.service.UserService;
import com.egoo.ticket.server.utils.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author：victor_tang
 * @Date ：2020/2/16
 * @Description：系统用户管理实现类
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
	@Autowired
	EwsUserDao ewsUserDao;
	@Autowired
	EwsUserRoleDao ewsUserRoleDao;
	@Autowired
	WorkOrderTypeNodeDao workOrderTypeNodeDao;
	@Autowired
	CommonUtil commonUtil;
	@Autowired
	RedisUtil redisUtil;
	@Value("${eurmSynData.limit}")
	private Integer limit;
	@Autowired
	private EurmDataSyncService eurmDataSyncService;
	@Value("${eurmSynData.tenantId}")
	private String eurmTenatIdCode;
	/**
	 * TODO 根据不同条件获取用户列表
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:40
	 * @param searchmap 1
	 * @return: java.utils.List<com.egoo.ews.service.vo.EwsUser>
	 */
	@Override
	public List<EwsUser> getAllUserList(Map<String, Object> searchmap) {
		return ewsUserDao.selectAllUserList(searchmap);
	}
	/**
	 * TODO 根据不同条件获取用户下拉label/value 列表
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:40
	 * @param searchMap 1
	 * @return: java.utils.List<com.egoo.ews.service.vo.InteractiveData>
	 */
	@Override
	public List<InteractiveDataVo> getInteractiveUsers(Map<String, Object> searchMap) {
		InteractiveDataVo interactiveDataVo = new InteractiveDataVo(ConstantCode.CurrentLoadUser.CURRENT_CREATOR_KEY,ConstantCode.CurrentLoadUser.CURRENT_CREATOR__VALUE,null,null,null,null);
		List<InteractiveDataVo> interactiveDataVos = ewsUserDao.selectInteractiveUsers(searchMap);
		interactiveDataVos.add(interactiveDataVo);
		return interactiveDataVos;
	}

	/**
	 * TODO 根据用户id查询用户信息
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:41
	 * @param id 1
	 * @return: com.egoo.ews.service.vo.EwsUser
	 */
	@Override
	public EwsUser selectById(String id) {
		return ewsUserDao.selectById(id);
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取用户名
	 * @Param:
	 * @return:
	 * @Date: 2020/10/30
	 */
	@Override
	public String selectNameById(String id) {
		EwsUser ewsUser = this.selectById(id);
		String name=null;
		if (!ObjectUtils.isEmpty(ewsUser)){
			name = ewsUser.getName();
		}
		return name;
	}

	/**
	 * TODO 批量更新用户数据和用户角色关系数据
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:41
	 * @param ewsUserList 1
	 * @param ewsUserRoleList 2
	 * @return: java.lang.Long
	 */
	@Override
	public Long addUserBatch(List<EwsUser> ewsUserList, List<EwsUserRole> ewsUserRoleList) {
		String tenantId = ewsUserList.get(0).getTenantId();
		ewsUserList.stream().map(ewsUser -> ewsUser.setTenantId(tenantId)).collect(Collectors.toList());
		ewsUserRoleList.stream().map(ewsUserRole -> ewsUserRole.setTenantId(tenantId)).collect(Collectors.toList());
		ewsUserRoleDao.insertBatch(ewsUserRoleList);
		return ewsUserDao.insertBatch(ewsUserList);
	}



	/**
	 * TODO 根据角色信息查询用户列表
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:42
	 * @param searchMap 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse getAllUserListByRoleInfo(Map<String, Object> searchMap) {

		List<EwsUser> dataList = ewsUserDao.selectUserListByRoleInfo(searchMap);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.SELECT_SUCCESS_MSG, dataList);
	}

	/**
	 * TODO 根据工单类型节点id获取坐席列表
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:43
	 * @param workOrderTypeNodeId 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse getUserListByWorkOrderTypeNodeId(String workOrderTypeNodeId, String tenantId) {

		WorkOrderTypeNodeVo workOrderTypeNodeVo = workOrderTypeNodeDao
				.getNodeByWorkOrderNodeId(Long.valueOf(workOrderTypeNodeId));
		if (workOrderTypeNodeVo == null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "未找到该工单类型节点信息！");
		}
		JSONObject content = workOrderTypeNodeVo.getContent();
		String type = content.getString("assigneetype");
		JSONArray assigneeJsonArray = content.getJSONArray("assignee");
		if (assigneeJsonArray==null || assigneeJsonArray.size()==0) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "未找到该工单类型节点的处理人信息！");
		}
		List<String> idList = null;
		if (ConstantCode.UserRoleDeptType.DEPT.equals(type)) {
			// 部门因为保存的是全链路信息，单独处理下
			idList = commonUtil.splitDeptCode(assigneeJsonArray.toJSONString());
		}else{
			idList = JSONObject.parseArray(assigneeJsonArray.toJSONString(), String.class);
		}
		// 获取类型节点处理人信息
		List<EwsUser> ewsUserList = getUserListByTypeAndTypeIds(type, idList, tenantId);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.SELECT_SUCCESS_MSG,
				ewsUserList);
	}
	/**
	 * TODO 根据用户ids获取用户名称组合
	 * @author: victor_tang
	 * @createtime: 2020/2/7 12:29
	 * @param userIds 1
	 * @return: java.lang.String
	 */
	@Override
	public String getNamesByUserIds(List<String> userIds,String tenantId) {
		if (userIds==null || userIds.size()==0) {
			return null;
		}
		StringBuffer userNames = new StringBuffer();
		Map<String, Object> searchmap = new HashMap<>(4);
		searchmap.put("userIds",userIds);
		searchmap.put("tenantId",tenantId);
		List<EwsUser> userList=
				ewsUserDao.selectAllUserList(searchmap);
		for (EwsUser ewsUser : userList) {
			userNames.append(ewsUser.getName()).append(",");
		}
		// 删除末尾逗号
		if (userNames!=null && userNames.length()>0) {

			userNames.deleteCharAt(userNames.length()-1);
			return userNames.toString();
		}
		return null;
	}
	/**
	 * TODO 根绝类型（role角色user用户）和类型ids获取用户列表
	 * @author: victor_tang
	 * @createtime: 2020/2/16 13:23
	 * @param type 1
	 * @param typeIds 2
	 * @return: java.utils.List<com.egoo.ews.service.vo.EwsUser>
	 */
	@Override
	public List<EwsUser> getUserListByTypeAndTypeIds(String type, List<String> typeIds,String tenantId) {
		Map<String, Object> searchMap = new HashMap<>(4);
		searchMap.put("tenantId",tenantId);
		if (ConstantCode.UserRoleDeptType.DEPT.equals(type)) {
			searchMap.put("departmentIds",typeIds);
			return ewsUserDao.selectAllUserList(searchMap);
		}
		else if (ConstantCode.UserRoleDeptType.ROLE.equals(type)) {
			searchMap.put("roleIds",typeIds);
			return ewsUserDao.selectUserListByRoleInfo(searchMap);
		}
		else if (ConstantCode.UserRoleDeptType.USER.equals(type)) {
			searchMap.put("userIds",typeIds);
			return ewsUserDao.selectAllUserList(searchMap);
		}
		return null;
	}

	/**
	 * TODO 根绝角色id列表获取用户列表
	 * @author: victor_tang
	 * @createtime: 2020/2/4 11:43
	 * @param roleIds 1
	 * @return: java.utils.List<com.egoo.ews.service.vo.EwsUser>
	 */
	private List<EwsUser> getUserListByRoleIds(List<String> roleIds,String tenantId) {

		Map<String, Object> searchMap = new HashMap<String, Object>(4);
		searchMap.put("roleIds", roleIds);
		searchMap.put("tenantId",tenantId);
		return ewsUserDao.selectUserListByRoleInfo(searchMap);
	}
}
